package com.neusoft.weekreport.component.bizService.impl;

import com.neusoft.weekreport.component.bizService.UserBizService;
import com.neusoft.weekreport.component.entities.*;
import com.neusoft.weekreport.component.req.*;
import com.neusoft.weekreport.component.resp.GetAddUserInfoResp;
import com.neusoft.weekreport.component.resp.GetUserInfoAfterGroupResp;
import com.neusoft.weekreport.component.resp.GetUserInfoByIdResp;
import com.neusoft.weekreport.component.resp.GetUserInfoListResp;
import com.neusoft.weekreport.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserBizServiceImpl implements UserBizService {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    MsUserMapper msUserMapper;
    @Resource
    BgUserRefRoleMapper bgUserRefRoleMapper;
    @Resource
    MsGroupRefUserMapper msGroupRefUserMapper;
    @Resource
    BgRoleMapper bgRoleMapper;
    @Resource
    MsGroupMapper msGroupMapper;
    @Resource
    DcProductMapper dcProductMapper;
    /**
     * 查询用户
     */
    @Override
    public GetUserInfoListResp getUserInfoList(GetUserInfoReq req){
        GetUserInfoListResp resp = new GetUserInfoListResp();
        MsUserExample msUserExample = new MsUserExample();
        MsUserExample.Criteria criteria = msUserExample.createCriteria();
        if(!StringUtils.isEmpty(req.getUserName())){
            criteria.andUserNameLike("%" + req.getUserName() +"%");
        }
        if(!StringUtils.isEmpty(req.getAccountValue())){
            criteria.andAccountNameLike("%" + req.getAccountValue() +"%");
        }
        if(req.getStateValue()==0){
            criteria.andEnableEqualTo(0);
        }
        if(req.getStateValue()==1){
            criteria.andEnableEqualTo(1);
        }
        if(!StringUtils.isEmpty(req.getId())){
            criteria.andIdEqualTo(req.getId());

        }
        msUserExample.setOrderByClause("UPDATE_DATE Desc");
        List<MsUser> msUsers = msUserMapper.selectByExample(msUserExample);
        resp.setUserInfos(msUsers);
        return resp;
    }

    // 添加用户
    @Override
    @Transactional
    public GetAddUserInfoResp addUserInfoList(GetAddUserInfoReq req) throws Exception {

        //插入用户表
        String userId=insertUserDb(req);
        //插入用户角色表
        insertUserRefRole(req, userId);
        //插入组和用户表
        inserGroupRefUser(req,userId);
        GetAddUserInfoResp resp = new GetAddUserInfoResp();
        resp.setId(userId);
        return  resp;

    }
    //查看用户信息
    @Override
    public GetUserInfoByIdResp getUserInfoById(GetUserInfoByIdReq req) throws Exception {

        //查询用户表
        GetUserInfoByIdResp  resp = new GetUserInfoByIdResp();
        MsUser msUser = msUserMapper.selectByPrimaryKey(req.getId());
        resp.setMsUser(msUser);

        //查询此用户负责的产品
        DcProductExample dcProductExample = new DcProductExample();
        DcProductExample.Criteria criteria4 = dcProductExample.createCriteria();
        criteria4.andUserIdEqualTo(req.getId());
        List<DcProduct> dcProductList = dcProductMapper.selectByExample(dcProductExample);
        resp.setDcProductList(dcProductList);

        //查询用户角色关系表
        BgUserRefRoleExample bgUserRefRoleExample = new BgUserRefRoleExample();
        BgUserRefRoleExample.Criteria criteria = bgUserRefRoleExample.createCriteria();
        criteria.andUserIdEqualTo(req.getId());
        List<BgUserRefRole> bgUserRefRoles =  bgUserRefRoleMapper.selectByExample(bgUserRefRoleExample);
        if(!bgUserRefRoles.isEmpty()){
            List<String> list = new ArrayList<>();
            for (BgUserRefRole bgUserRefRole : bgUserRefRoles) {
                list.add(bgUserRefRole.getRoleId());
            }
            BgRoleExample bgRoleExample = new BgRoleExample();
            BgRoleExample.Criteria criteria1 = bgRoleExample.createCriteria();
            criteria1.andIdIn(list);
            List<BgRole> bgRoles = bgRoleMapper.selectByExample(bgRoleExample);
            resp.setBgRoleList(bgRoles);
        }else{
            List<BgRole> bgRoles = new ArrayList<>();
            resp.setBgRoleList(bgRoles);
        }

        //查询组和用户关系表
        MsGroupRefUserExample msGroupRefUserExample = new MsGroupRefUserExample();
        MsGroupRefUserExample.Criteria criteria2 = msGroupRefUserExample.createCriteria();
        criteria2.andUseridEqualTo(req.getId());
        List<MsGroupRefUser> msGroupRefUsers = msGroupRefUserMapper.selectByExample(msGroupRefUserExample);
        if(!msGroupRefUsers.isEmpty()){
            List<String> list2 = new ArrayList<>();
            for (MsGroupRefUser msGroupRefUser : msGroupRefUsers) {
                list2.add(msGroupRefUser.getGroupid());
            }
            MsGroupExample msGroupExample = new MsGroupExample();
            MsGroupExample.Criteria criteria3 = msGroupExample.createCriteria();
            criteria3.andIdIn(list2);
            List<MsGroup> msGroups = msGroupMapper.selectByExample(msGroupExample);
            resp.setMsGroupsList(msGroups);
        }else{
            List<MsGroup> msGroups = new ArrayList<>();
            resp.setMsGroupsList(msGroups);
        }
        return resp;
    }

    //修改用户信息
    @Override
    @Transactional
    public void editUserInfoList(GetAddUserInfoReq req) throws Exception {

        //更新用户表
        MsUser msUser = new MsUser();
        String UpdateDate = sysDateTime();
        msUser.setId(req.getId());
        msUser.setAccountName(req.getAccountName());
        msUser.setUserName(req.getUserName());
        msUser.setEmailAddress(req.getEmailAddress());
        msUser.setSummary(req.getSummary());
        msUser.setUpdateDate(UpdateDate);
        msUserMapper.updateByPrimaryKeySelective(msUser);

        //更新用户角色关系表
        UpdateUserRole(req);

        //更新用户组关系表
        UpdateGroupUser(req);
    }

    //修改用户状态
    @Override
    public void changeUserStatus(GetChangeUserStatusReq req) throws Exception {
        String UpdateDate = sysDateTime();
        MsUser msUser = new MsUser();
        msUser.setId(req.getId());
        Integer enable;
        if(req.getEnable()==1){
            enable = 0;
        }else{
            enable = 1;
        }
        msUser.setEnable(enable);
        msUser.setUpdateDate(UpdateDate);
        msUserMapper.updateByPrimaryKeySelective(msUser);
    }

    //删除用户
    @Override
    @Transactional
    public void deleteUser(GetChangeUserStatusReq req) throws Exception {

        //删除用户
        msUserMapper.deleteByPrimaryKey(req.getId());

        //删除用户和角色关联表
        BgUserRefRoleExample bgUserRefRoleExample = new BgUserRefRoleExample();
        BgUserRefRoleExample.Criteria criteria = bgUserRefRoleExample.createCriteria();
        criteria.andUserIdEqualTo(req.getId());
        bgUserRefRoleMapper.deleteByExample(bgUserRefRoleExample);

        //删除用户和组关联表
        MsGroupRefUserExample msGroupRefUserExample = new MsGroupRefUserExample();
        MsGroupRefUserExample.Criteria criteria1 = msGroupRefUserExample.createCriteria();
        criteria1.andUseridEqualTo(req.getId());
        msGroupRefUserMapper.deleteByExample(msGroupRefUserExample);

    }

    //重置用户密码
    @Override
    public void userPwdReset(GetChangeUserStatusReq req) throws Exception {
        String UpdateDate = sysDateTime();
        MsUser msUser = new MsUser();
        msUser.setId(req.getId());
        msUser.setPassword("123456");
        msUser.setUpdateDate(UpdateDate);
        msUserMapper.updateByPrimaryKeySelective(msUser);
    }

    private void UpdateUserRole(GetAddUserInfoReq req){

        //根据userid，删除用户角色关联表中的数据
        String userId = req.getId();
        BgUserRefRoleExample bgUserRefRoleExample = new BgUserRefRoleExample();
        BgUserRefRoleExample.Criteria criteria = bgUserRefRoleExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        bgUserRefRoleMapper.deleteByExample(bgUserRefRoleExample);

        //insert用户关联表
        insertUserRefRole(req,userId);

    }

    private  void UpdateGroupUser(GetAddUserInfoReq req){

        //根据userid，删除组和用户关联表数据
        String userId = req.getId();
        MsGroupRefUserExample msGroupRefUserExample = new MsGroupRefUserExample();
        MsGroupRefUserExample.Criteria criteria = msGroupRefUserExample.createCriteria();
        criteria.andUseridEqualTo(userId);
        msGroupRefUserMapper.deleteByExample(msGroupRefUserExample);

        //insert用户关联表
        inserGroupRefUser(req,userId);
    }

    //修改密码
    @Override
    public void modifyPassword(GetModifyPasswordReq req) throws Exception {
        MsUser msUser = new MsUser();
        msUser.setId(req.getId());
        msUser.setPassword(req.getNewPassword());
        msUserMapper.updateByPrimaryKeySelective(msUser);
    }

    //如果是组长，返回组员，如果是组员，返回自己
    @Override
    public GetUserInfoAfterGroupResp  getGroupAfterUser(GetUserInfoByIdReq req) throws Exception{
        GetUserInfoAfterGroupResp resp = new GetUserInfoAfterGroupResp();

        //查询出部门
        String department = getUserDepartmentInfo(req);
        resp.setDepartment(department);

        BgUserRefRoleExample bgUserRefRoleExample = new BgUserRefRoleExample();
        BgUserRefRoleExample.Criteria criteria = bgUserRefRoleExample.createCriteria();
        criteria.andUserIdEqualTo(req.getId());
        List<BgUserRefRole> bgUserRefRoleList = bgUserRefRoleMapper.selectByExample(bgUserRefRoleExample);

        //查询出下面的人userAll
        MsUserExample msUserExample = new MsUserExample();
        MsUserExample.Criteria criteria1 = msUserExample.createCriteria();

        //查询出不需要写周报的组
        MsGroupExample noWeekmsGroupExample = new MsGroupExample();
        MsGroupExample.Criteria NoWeekCriteria = noWeekmsGroupExample.createCriteria();
        NoWeekCriteria.andWeekFlagNotEqualTo(1);//不等于
        //判断用户角色关联表查询结果是否为空
        if(!CollectionUtils.isEmpty(bgUserRefRoleList)){
            List<String> roleIdList = new ArrayList<>();
            for (BgUserRefRole bgUserRefRole : bgUserRefRoleList) {
                roleIdList.add(bgUserRefRole.getRoleId());
//                userIdList.add(bgUserRefRole.getUserId());
            }
            if(roleIdList.contains("10002")){//是组长
                MsGroupRefUserExample msGroupRefUserExample = new MsGroupRefUserExample();
                MsGroupRefUserExample.Criteria criteria2 = msGroupRefUserExample.createCriteria();
                criteria2.andUseridEqualTo(req.getId());
                List<MsGroupRefUser> msGroupRefUserList = msGroupRefUserMapper.selectByExample(msGroupRefUserExample);
                if(!CollectionUtils.isEmpty(msGroupRefUserList)){
                    List<String> groupIdList = new ArrayList<>();
                    for (MsGroupRefUser msGroupRefUser : msGroupRefUserList) {
                        groupIdList.add(msGroupRefUser.getGroupid());
                    }
                    //查询出不需要写周报的组
                    NoWeekCriteria.andIdIn(groupIdList);
                    //
                    msGroupRefUserExample.clear();
                    criteria2 = msGroupRefUserExample.createCriteria();
                    criteria2.andGroupidIn(groupIdList);
                    List<MsGroupRefUser> msGroupRefUserList1 = msGroupRefUserMapper.selectByExample(msGroupRefUserExample);
                    List<String> userIdList1 = new ArrayList<>();
                    for (MsGroupRefUser msGroupRefUser : msGroupRefUserList1) {
                        userIdList1.add(msGroupRefUser.getUserid());
                    }
                    //查询领导userId
                    BgUserRefRoleExample bgUserRefRoleExample1=new BgUserRefRoleExample();
                    BgUserRefRoleExample.Criteria criteria3 = bgUserRefRoleExample1.createCriteria();
                    criteria3.andRoleIdEqualTo("10004");
                    List<BgUserRefRole> lists = bgUserRefRoleMapper.selectByExample(bgUserRefRoleExample1);
                    List<String> userIdLead = new ArrayList<>();
                    if(!CollectionUtils.isEmpty(lists)){
                        for (BgUserRefRole list : lists) {
                            userIdLead.add(list.getUserId());
                        }
                    }
                    //去除领导userId
                    List<String> newUseridList = new ArrayList<>();
                    for (String userId : userIdList1) {
                        if(userIdLead.contains(userId)){
                            continue;
                        }else{
                            newUseridList.add(userId);
                        }

                    }
                    criteria1.andIdIn(newUseridList);
                }else{
                    criteria1.andIdEqualTo(req.getId());
                }


            }else if(roleIdList.contains("10004")||roleIdList.contains("10001")){//领导
                MsGroupRefUserExample msGroupRefUserExample = new MsGroupRefUserExample();
                MsGroupRefUserExample.Criteria criteria2 = msGroupRefUserExample.createCriteria();
                criteria2.andUseridEqualTo(req.getId());
                List<MsGroupRefUser> msGroupRefUserList = msGroupRefUserMapper.selectByExample(msGroupRefUserExample);
                if(!CollectionUtils.isEmpty(msGroupRefUserList)){
                    List<String> groupIdList = new ArrayList<>();
                    for (MsGroupRefUser msGroupRefUser : msGroupRefUserList) {
//                        List<String>  allGroupIdList= getALlGroup(GroupIdList,msGroupRefUser.getGroupid());
                        MsGroupExample msGroupExample = new MsGroupExample();
                        MsGroupExample.Criteria criteria3 = msGroupExample.createCriteria();
                        criteria3.andParentIdEqualTo(msGroupRefUser.getGroupid());
                        List<MsGroup> msGroupList = msGroupMapper.selectByExample(msGroupExample);
                        if(!CollectionUtils.isEmpty(msGroupList)){
                            for (MsGroup msGroup : msGroupList) {
                                groupIdList.add(msGroup.getId());
                            }
//                            groupIdList.addAll(allGroupIdList);
                        }else{
                            groupIdList.add(msGroupRefUser.getGroupid());
                        }
                    }
                    //查询出不需要写周报的组
                    NoWeekCriteria.andIdIn(groupIdList);
                    //
                    msGroupRefUserExample.clear();
                    criteria2 = msGroupRefUserExample.createCriteria();
                    criteria2.andGroupidIn(groupIdList);
                    List<MsGroupRefUser> msGroupRefUserList1 = msGroupRefUserMapper.selectByExample(msGroupRefUserExample);
                    List<String> userIdList1 = new ArrayList<>();
                    for (MsGroupRefUser msGroupRefUser : msGroupRefUserList1) {
                        userIdList1.add(msGroupRefUser.getUserid());
                    }
                    criteria1.andIdIn(userIdList1);
                }else{
                    criteria1.andIdEqualTo(req.getId());
                }
            }
            else{ //非组长按照普通员工处理
                criteria1.andIdEqualTo(req.getId());
            }
        }else{ //用户无角色按照普通员工处理
            criteria1.andIdEqualTo(req.getId());
        }
        //查询出下面所有user
        criteria1.andEnableEqualTo(1);
        msUserExample.setOrderByClause("user_name");
        List<MsUser> msUserList = msUserMapper.selectByExample(msUserExample);

        //查询出不能填写周报的组
        List<MsGroup> noWeekGroupList = msGroupMapper.selectByExample(noWeekmsGroupExample);
        List<String> noWeekGroupIdList = new ArrayList<>();//定义不需要写周报的组
        for (MsGroup msGroup : noWeekGroupList) {
            noWeekGroupIdList.add(msGroup.getId());
        }
        List<Map<String,String>> userAllListMap = new ArrayList<Map<String, String>>();
        userAllListMap = getUserAndGroupInfo(msUserList);
        resp.setUsermapList(userAllListMap);
        resp.setNoWeekGroupList(noWeekGroupIdList);
        return resp;
    }

    public List<Map<String,String>>  getUserAndGroupInfo(List<MsUser> msUserList){
        List<Map<String,String>> listMap = new ArrayList<Map<String, String>>();
        for (MsUser msUser : msUserList) {
            Map<String,String> map = new HashMap<>();
            map.put("code",msUser.getId());
            map.put("value",msUser.getUserName());
            MsGroupRefUserExample msGroupRefUserExample = new MsGroupRefUserExample();
            MsGroupRefUserExample.Criteria criteria2 = msGroupRefUserExample.createCriteria();
            criteria2.andUseridEqualTo(msUser.getId());
            List<MsGroupRefUser> msGroupRefUserList = msGroupRefUserMapper.selectByExample(msGroupRefUserExample);
            for (MsGroupRefUser msGroupRefUser : msGroupRefUserList) {
                map.put("groupId",msGroupRefUser.getGroupid());
                break;
            }
            if(CollectionUtils.isEmpty(listMap)){
                listMap.add(map);
            }else{
                if(!listMap.contains(map)){
                    listMap.add(map);
                }
            }
        }
        return listMap;
    }
//    //递归查询所有组
//    public List<String> getALlGroup(List<String> GroupIdList,String groupId){
//
//        MsGroupExample msGroupExample = new MsGroupExample();
//        MsGroupExample.Criteria criteria3 = msGroupExample.createCriteria();
//        criteria3.andParentIdEqualTo(groupId);
//        List<MsGroup> msGroupList = msGroupMapper.selectByExample(msGroupExample);
//        if(!CollectionUtils.isEmpty(msGroupList)){
//            for (MsGroup msGroup : msGroupList) {
//                GroupIdList.add(msGroup.getId());
//                getALlGroup(GroupIdList,msGroup.getId());
//            }
//        }else{
//            GroupIdList.add(groupId);
//        }
//        return GroupIdList;
//    }
    //查询用户所属部门
    public String getUserDepartmentInfo(GetUserInfoByIdReq req){
        MsGroupRefUserExample msGroupRefUserExample = new MsGroupRefUserExample();
        MsGroupRefUserExample.Criteria criteria = msGroupRefUserExample.createCriteria();
        criteria.andUseridEqualTo(req.getId());
        List<MsGroupRefUser> msGroupRefUserList = msGroupRefUserMapper.selectByExample(msGroupRefUserExample);
        String groupId="";
        for (MsGroupRefUser msGroupRefUser : msGroupRefUserList) {
            groupId = msGroupRefUser.getGroupid();
            break;
        }
        String department = recuisiveQuery(groupId);
        return department;
    }
    public String recuisiveQuery(String groupId){
        String department="";
        MsGroup msGroup =  msGroupMapper.selectByPrimaryKey(groupId);
        if(msGroup.getParentId().equals("-1")){
            department=msGroup.getGroupName();

        }else{
            department=recuisiveQuery(msGroup.getParentId());
        }
        return department;
    }



    private String insertUserDb(GetAddUserInfoReq req) {

        String userId = UUID.randomUUID().toString();
        String createDate = sysDateTime();
        MsUser msUser = new MsUser();
        msUser.setId(userId);
        msUser.setAccountName(req.getAccountName());
        msUser.setEmailAddress(req.getEmailAddress());
        msUser.setUserName(req.getUserName());
        msUser.setSummary(req.getSummary());
        msUser.setPassword("123456");
        msUser.setEnable(1);
        msUser.setCreateDate(createDate);
        msUser.setUpdateDate(createDate);
        msUser.setCreateBy(req.getCREATE_BY());
        msUserMapper.insert(msUser);
        return userId;
    }

    private void insertUserRefRole(GetAddUserInfoReq req, String userId) {
        BgUserRefRole bgUserRefRole = new BgUserRefRole();
        List<String> roleList = req.getRoleIdList();
        for (String roleId : roleList) {
            bgUserRefRole.setRoleId(roleId);
            bgUserRefRole.setUserId(userId);
            bgUserRefRoleMapper.insert(bgUserRefRole);
        }
    }
    private void inserGroupRefUser(GetAddUserInfoReq req, String userId){
        MsGroupRefUser msGroupRefUser = new MsGroupRefUser();
        List<String> groupList = req.getGroupIdList();
        for (String groupId : groupList) {
            msGroupRefUser.setGroupid(groupId);
            msGroupRefUser.setUserid(userId);
            msGroupRefUserMapper.insert(msGroupRefUser);
        }
    }

    private String sysDateTime(){
        Date date = new Date();
        DateFormat dataFormat = new SimpleDateFormat("yyy-MM-dd hh:mm:ss");
        String createDate = dataFormat.format(date);
        return createDate;
    }
}
